<template>
  <div class="app-container">
    <div class="top-bar-container">
      <el-row>
        <el-col :span="16">
          <div class="search-container">
            <search-form @search-submit="getSysUserList">
              <search-input v-model="listQuery.id" placeholder="ID" />
              <search-input v-model="listQuery.username" placeholder="用户名" />
              <search-input v-model="listQuery.mobile" placeholder="手机号" />
              <search-select-dict v-model="listQuery.status" :dict="enableStatusList" placeholder="状态" />
            </search-form>
          </div>
        </el-col>
        <el-col :span="8">
          <el-row type="flex" justify="end">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreateSysUser">新增系统用户
            </el-button>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit stripe highlight-current-row>
      <el-table-column align="center" label="ID">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!--      <el-table-column align="center" label="机构">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ agenciesMap[row.agenciesId] }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column align="center" label="用户名">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="手机号">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status | enableStatusFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间">
        <template slot-scope="{row}">
          <span>{{ row.createdTime }}</span>
        </template>
      </el-table-column>

      <!--      <el-table-column align="center" label="更新时间">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.updatedTime }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        width="360"
      >
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-share"
              title="分配角色"
              @click="handleAssignRoleRow(scope.$index)"
            >分配角色
            </el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              title="重置密码"
              @click="handleResetSysUserRow(scope.$index)"
            >重置密码
            </el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-edit"
              title="编辑"
              @click="handleEditSysUserRow(scope.$index)"
            >编辑
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除"
              @click="handleDeleteSysUserRow(scope.$index)"
            >删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getSysUserList"
    />

    <el-dialog
      title="新增系统用户"
      :visible.sync="dialogCreateVisible"
      width="500px"
      @close="handleCreateFormDialogClose"
    >
      <el-form
        ref="createForm"
        :model="createForm"
        :rules="createRules"
        class="create-form"
        autocomplete="on"
        label-position="right"
      >

        <el-form-item prop="username" label="机构" label-width="80px">
          <el-select v-model="createForm.agenciesId" placeholder="请选择">
            <el-option
              v-for="item in agenciesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="用户名" label-width="80px">
          <el-input v-model="createForm.username" />
        </el-form-item>
        <el-form-item prop="mobile" label="手机号" label-position="right" label-width="80px">
          <el-input v-model="createForm.mobile" />
        </el-form-item>
        <el-form-item prop="status" label="状态" label-width="80px">
          <el-select v-model="createForm.status" placeholder="请选择">
            <el-option
              v-for="item in enableStatusList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="password" label="初始密码" label-position="right" label-width="80px">
          <el-input v-model="createForm.password" type="password" />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" label-position="right" label-width="80px">
          <el-input v-model="createForm.confirmPassword" type="password" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveCreateSysUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑系统用户"
      :visible.sync="dialogEditVisible"
      width="500px"
      @close="handleEditFormDialogClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        class="edit-form"
        autocomplete="on"
        label-position="right"
      >
        <el-form-item prop="username" label="机构" label-width="80px">
          <el-select v-model="editForm.agenciesId" placeholder="请选择">
            <el-option
              v-for="item in agenciesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="用户名" label-width="80px">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机号"
          label-position="right"
          label-width="80px"
          :rules="[{ trigger: 'blur', validator: elValidatePhone }]"
        >
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item prop="status" label="状态" label-width="80px">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option
              v-for="item in enableStatusList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveEditSysUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="重置密码"
      :visible.sync="dialogResetVisible"
      width="500px"
      @close="handleResetFormDialogClose"
    >
      <el-form
        ref="resetForm"
        :model="resetForm"
        :rules="resetRules"
        class="reset-form"
        autocomplete="on"
        label-position="right"
      >
        <el-form-item prop="newPassword" label="重置密码" label-position="right" label-width="80px">
          <el-input v-model="resetForm.newPassword" type="password" />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" label-position="right" label-width="80px">
          <el-input v-model="resetForm.confirmPassword" type="password" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogResetVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveResetSysUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分配角色"
      :visible.sync="dialogAssignVisible"
      width="500px"
      @close="handleAssignDialogClose"
    >
      <el-row>
        <el-col :span="12">
          <el-tree
            ref="roleTree"
            :data="roleTreeData"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="roleTreeDefaultCheckedKeys"
            :props="roleTreeProps"
            @check="changeRole"
          />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveAssignSysUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue'
import SearchForm from '@/components/SearchForm/index.vue'
import SearchInput from '@/components/SearchForm/SearchInput/index.vue'
import SearchSelectDict from '@/components/SearchForm/SearchSelectDict/index.vue'
import {
  adminGetUserTypeRelList,
  adminSysUserAssignRole,
  adminSysUserCheckableDivisionList,
  adminSysUserCheckableRoleList,
  adminSysUserCheckAvailable,
  adminSysUserCreate,
  adminSysUserDelete,
  adminSysUserList,
  adminSysUserResetPassword,
  adminSysUserUpdate
} from '@/api/rest/admin'
import { elPasswordRule, elPhoneNumRule, elRequiredChangeRule, elRequiredRule } from '@/utils/el-validator'
import { enableStatusList } from '@/utils/dict'
import rs from 'jsrsasign'
import { mapState } from 'vuex'
import visuUtil from '@/utils/visu-util'

const initForm = {
  id: null,
  agenciesId: null,
  username: null,
  mobile: null,
  status: null,
  password: null,
  confirmPassword: null
}

export default {
  name: 'SysUserList',
  components: { Pagination, SearchInput, SearchForm, SearchSelectDict },
  data() {
    const validateUsernameAvailable = (rule, value, callback) => {
      return adminSysUserCheckAvailable(value, this.editForm.id).then(resp => {
        if (!resp.data) {
          callback(new Error('用户名已存在'))
        } else {
          callback()
        }
      })
    }

    const validateCreateConfirmPassword = (rule, value, callback) => {
      if (value !== this.createForm.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }

    const validateResetConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetForm.newPassword) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }

    return {
      list: null,
      total: 0,
      listLoading: true,
      communityList: [],
      listQuery: {
        id: null,
        username: null,
        page: 1,
        limit: 10
      },
      originalMobile: null,
      createForm: { ...initForm },
      createRules: {
        username: [elRequiredRule, { trigger: 'blur', validator: validateUsernameAvailable }],
        mobile: elPhoneNumRule,
        status: elRequiredChangeRule,
        password: [elRequiredRule, elPasswordRule],
        confirmPassword: [elRequiredRule, { trigger: 'blur', validator: validateCreateConfirmPassword }]
      },
      editForm: {
        id: null,
        agenciesId: null,
        username: null,
        mobile: null,
        status: null
      },
      editRules: {
        username: [{ trigger: 'blur', validator: validateUsernameAvailable }, elRequiredRule],
        mobile: elPhoneNumRule,
        status: elRequiredChangeRule
      },
      resetForm: {
        id: null,
        newPassword: null,
        confirmPassword: null
      },
      resetRules: {
        newPassword: [elRequiredRule, elPasswordRule],
        confirmPassword: [elRequiredRule, { trigger: 'blur', validator: validateResetConfirmPassword }]
      },
      roleAssignSysUserId: null,
      roleTreeData: null,
      roleTreeDefaultCheckedKeys: null,
      roleCheckedCode: [],
      refIdList: [],
      communityId: null,
      roleTreeProps: {
        label: 'name'
      },
      divisionTreeData: null,
      divisionTreeDefaultCheckedKeys: null,
      divisionTreeProps: {
        label: 'areaName'
      },
      dialogEditVisible: false,
      dialogCreateVisible: false,
      dialogResetVisible: false,
      dialogAssignVisible: false,
      enableStatusList: enableStatusList,
      provinceCode: visuUtil.defaultAreaCodeData,
      agenciesList: [],
      agenciesMap: {}
    }
  },
  computed: {
    ...mapState({
      publicKey: (state) => state.user.publicKey
    })
  },
  created() {
    this.getSysUserList()
  },
  methods: {
    elValidatePhone(rule, value, callback) {
      if (value === this.originalMobile) {
        callback()
        return
      }
      if (value && !/^1[3456789]\d{9}$/.test(value) && !/^((0\d{2,3})-)(\d{7,8})(-(\d[1-4]))?$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    },
    getSysUserList() {
      this.listLoading = true
      adminSysUserList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleEditSysUserRow(index) {
      this.editForm = { ...this.list[index] }
      this.originalMobile = this.editForm.mobile
      this.dialogEditVisible = true
    },
    handleDeleteSysUserRow(index) {
      const data = this.list[index]
      this.$confirm('此操作将删除系统用户, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        adminSysUserDelete(data.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除系统用户成功'
          })
          this.getSysUserList()
        }).catch(() => {
        })
      })
    },
    handleCreateSysUser() {
      this.createForm = { ...initForm }
      this.dialogCreateVisible = true
    },
    handleSaveCreateSysUser() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          const postForm = {
            ...this.createForm,
            password: rs.KJUR.crypto.Cipher.encrypt(this.createForm.password, this.publicKey),
            confirmPassword: rs.KJUR.crypto.Cipher.encrypt(this.createForm.confirmPassword, this.publicKey)
          }
          adminSysUserCreate(postForm).then(response => {
            this.$message({
              message: '新增系统用户成功',
              type: 'success'
            })
            this.getSysUserList()
            this.dialogCreateVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSaveEditSysUser() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          adminSysUserUpdate(this.editForm).then(response => {
            this.$message({
              message: '编辑系统用户成功',
              type: 'success'
            })
            this.getSysUserList()
            this.dialogEditVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCreateFormDialogClose() {
      this.$refs.createForm.clearValidate()
    },
    handleEditFormDialogClose() {
      this.$refs.editForm.clearValidate()
    },
    handleResetFormDialogClose() {
      this.$refs.resetForm.clearValidate()
    },
    handleResetSysUserRow(index) {
      const { id } = this.list[index]
      this.resetForm = {
        id: id,
        newPassword: null,
        confirmPassword: null
      }
      this.dialogResetVisible = true
    },
    handleSaveResetSysUser() {
      this.$refs.resetForm.validate(valid => {
        if (valid) {
          const postForm = {
            ...this.resetForm,
            newPassword: rs.KJUR.crypto.Cipher.encrypt(this.resetForm.newPassword, this.publicKey),
            confirmPassword: rs.KJUR.crypto.Cipher.encrypt(this.resetForm.confirmPassword, this.publicKey)
          }
          adminSysUserResetPassword(postForm).then(response => {
            this.$message({
              message: '重置系统用户密码成功',
              type: 'success'
            })
            this.dialogResetVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    changeRole(data, checked, indeterminate) {
      this.roleCheckedCode = checked.checkedNodes.map(r => r.code)
    },
    handleAssignDialogClose() {
      this.roleAssignSysUserId = null
      this.roleTreeData = null
      this.roleTreeDefaultCheckedKeys = null
      this.divisionTreeData = null
      this.divisionTreeDefaultCheckedKeys = null
    },
    handleAssignRoleRow(index) {
      const that = this
      const { id } = this.list[index]
      this.roleAssignSysUserId = id
      adminSysUserCheckableRoleList(id).then(response => {
        this.roleTreeData = response.data.map(r => r.role)
        this.roleTreeDefaultCheckedKeys = response.data.filter(r => r.checked).map(r => r.role.id)
        this.roleCheckedCode = response.data.filter(r => r.checked).map(r => r.role.code)
        this.dialogAssignVisible = true
        adminSysUserCheckableDivisionList(id).then(response2 => {
          this.divisionTreeData = response2.data.map(r2 => r2.division)
          this.divisionTreeDefaultCheckedKeys = response2.data.filter(r2 => r2.checked).map(r2 => r2.division.id)
          this.dialogAssignVisible = true
        })

        adminGetUserTypeRelList(id).then(response3 => {
          if (response3.data.length > 0) {
            response3.data.forEach(item => {
              if (item.userType === 30) {
                that.communityId = item.objectId
              }
            })
          }
        })
      })
      this.getCommunityList()
    },
    handleSaveAssignSysUser() {
      const checkedRoleIds = this.$refs.roleTree.getCheckedKeys()
      const checkedDivisionIds =
        (this.$refs.divisionTree) ? this.$refs.divisionTree.getCheckedKeys() : []
      adminSysUserAssignRole({
        sysUserId: this.roleAssignSysUserId,
        checkedRoleIds,
        checkedDivisionIds,
        communityId: this.communityId
      }).then(response => {
        this.$message({
          message: '分配系统用户角色成功',
          type: 'success'
        })
        this.dialogAssignVisible = false
      })
    }
  }
}
</script>
<style scoped>
</style>

